import 'package:boss/models/coupon.dart';
import 'package:boss/textStyle/text_style.dart';
import 'package:boss/ui/page/binding/widget/upload_image.dart';
import 'package:boss/ui/page/commodity/categories/page/plusCommodityMode/page/plusPackage/widget/package_panel.dart';
import 'package:boss/ui/page/marketing/coupon/couponDetail/modal/edit_coupon_share_modal.dart';
import 'package:boss/ui/page/marketing/coupon/couponDetail/provider/coupon_detail_provider.dart';
import 'package:boss/ui/widget/button/fixed_bottom_btn.dart';
import 'package:boss/ui/widget/calendar_bar.dart';
import 'package:boss/ui/widget/column_divier.dart';
import 'package:boss/ui/widget/form/base_text_form_field.dart';
import 'package:boss/ui/widget/form/chip_form_field.dart';
import 'package:boss/ui/widget/form/long_text_form_field.dart';
import 'package:boss/ui/widget/form/select_form_field.dart';
import 'package:boss/ui/widget/label_button.dart';
import 'package:boss/ui/widget/radioList/radio.dart' as radio;
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:hi_common/hi_common.dart';
import 'package:provider/provider.dart';


class CouponDetailBrowser extends StatefulWidget {
  @override
  _CouponDetailBrowserState createState() => _CouponDetailBrowserState();
}

class _CouponDetailBrowserState extends State<CouponDetailBrowser> {
  final startTodayFocusNode = FocusNode();
  final startTomorrowFocusNode = FocusNode();

  @override
  void initState() {
    super.initState();

    final provider = Provider.of<CouponDetailProvider>(context, listen: false);

    startTodayFocusNode.addListener(() {
      if (startTodayFocusNode.hasFocus) {
        provider.setTimeLimitType(Coupon.TIME_TODAY);
      }
    });

    startTomorrowFocusNode.addListener(() {
      if (startTomorrowFocusNode.hasFocus) {
        provider.setTimeLimitType(Coupon.TIME_TOMORROW);
      }
    });
  }

  @override
  void dispose() {
    startTodayFocusNode.dispose();
    startTomorrowFocusNode.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Consumer<CouponDetailProvider>(
      builder: (context, provider, _) => DefaultTextStyle(
        style: TextStyleConstant().normal_1_28,
        child: Column(
          children: <Widget>[
            Expanded(
              child: SingleChildScrollView(
                padding: EdgeInsets.zero,
                child: ColumnDivier(
                  padding: EdgeInsets.symmetric(horizontal: 30.w),
                  children: <Widget>[
                    Column(
                      children: <Widget>[
                        BaseTextFormField(
                          prefixText: '优惠券名称',
                          maxLength: 10,
                          isRequired: true,
                          hintText: '请输入优惠券名称',
                          initialValue: provider.coupon.couponName,
                          enabled: provider.isCouponOn,
                          onChanged: (value) {
                            provider.coupon.couponName = value;
                          },
                        ),
                        SelectFormField(
                          enabled: provider.isCouponOn,
                          title: '优惠券类型',
                          items: [
                            SelectItem(title: '代金劵', value: Coupon.TYPE_CASH),
                            SelectItem(title: '折扣劵', value: Coupon.TYPE_DISCOUNT),
                          ],
                          value: provider.coupon.couponType,
                          onChanged: provider.setCouponType,
                        ),
                        if (provider.coupon.couponType == Coupon.TYPE_CASH)
                          BaseTextFormField(
                            key: ValueKey('cash'),
                            enabled: provider.isCouponOn,
                            prefixText: '代金券',
                            isRequired: true,
                            hintText: '请输入抵扣金额',
                            suffixText: '元',
                            maxLength: 5,
                            keyboardType: TextInputType.number,
                            initialValue: provider.couponDiscountAmountText,
                            onChanged: provider.setCouponDiscountAmount,
                            inputFormatters: [FilteringTextInputFormatter.allow(RegUtil.numberReg)],
                          ),
                        if (provider.coupon.couponType == Coupon.TYPE_DISCOUNT)
                          BaseTextFormField(
                            key: ValueKey('discount'),
                            enabled: provider.isCouponOn,
                            prefixText: '折扣券',
                            isRequired: true,
                            hintText: '请输入抵扣金额',
                            suffixText: '折',
                            maxLength: 3,
                            keyboardType: TextInputType.numberWithOptions(decimal: true),
                            initialValue: provider.couponDiscountAmountText,
                            onChanged: provider.setCouponDiscountAmount,
                            inputFormatters: [FilteringTextInputFormatter.allow(RegUtil.numberReg)],
                          ),
                        BaseTextFormField(
                          enabled: provider.isCouponOn,
                          prefixText: '使用门槛',
                          hintText: '不含邮费，不填则无门槛',
                          suffixText: '元',
                          maxLength: 9,
                          keyboardType: TextInputType.number,
                          initialValue: provider.usingThresholdText,
                          onChanged: provider.setUsingThreshold,
                          inputFormatters: [FilteringTextInputFormatter.allow(RegUtil.numberReg)],
                        ),
                        ChipFormField(
                          enabled: provider.isCouponOn,
                          multiple: false,
                          title: RichText(
                            text: TextSpan(
                              text: '使用范围',
                              style: TextStyleConstant().normal_1_28,
                              children: [
                                TextSpan(text: '(可使用券范围)', style: TextStyleConstant().normal_3_24),
                              ],
                            ),
                          ),
                          items: [
                            ChipFormData(title: '堂食', value: Coupon.USE_RANGE_DINNER),
                            ChipFormData(title: '外卖', value: Coupon.USE_RANGE_TAKEOUT),
                            // ChipFormData(title: '电商', value: Coupon.USE_RANGE_SHOP),
                          ],
                          selectedItems: provider.usingRange,
                          onChanged: provider.setCouponUseRange,
                        ),
                        BaseTextFormField(
                          enabled: provider.isCouponOn,
                          prefixText: '员工分享分红',
                          hintText: '核销过后奖励金额',
                          suffixText: '元',
                          keyboardType: TextInputType.numberWithOptions(decimal: true),
                          initialValue: provider.waiterShareBonusText,
                          onChanged: provider.setWaiterShareBonus,
                          inputFormatters: [FilteringTextInputFormatter.allow(RegUtil.numberReg)],
                        ),
                        BaseTextFormField(
                          enabled: provider.isCouponOn,
                          prefixText: '用户分享分红',
                          hintText: '核销过后奖励抵扣金额',
                          suffixText: '元',
                          keyboardType: TextInputType.numberWithOptions(decimal: true),
                          initialValue: provider.userShareBonusText,
                          onChanged: provider.setUserShareBonus,
                          inputFormatters: [FilteringTextInputFormatter.allow(RegUtil.numberReg)],
                        ),
                        BaseTextFormField(
                          enabled: provider.isCouponOn,
                          prefixText: '发券总量',
                          hintText: '不填则无限制',
                          suffixText: '张',
                          keyboardType: TextInputType.number,
                          maxLength: 9,
                          initialValue: provider.coupon.couponTotalNum?.toString(),
                          onChanged: provider.setCouponTotalNum,
                          inputFormatters: [FilteringTextInputFormatter.allow(RegUtil.integerReg)],
                        ),
                      ],
                    ),
                    PackagePanel(
                      title: '使用期限',
                      isRequired: true,
                      contentPadding: EdgeInsets.zero,
                      padding: EdgeInsets.zero,
                      children: <Widget>[
                        _RadioRow(
                          isSelected: provider.coupon.timeLimitType == Coupon.TIME_ABSOLUTELY,
                          onSelectedChange: (_) {
                            provider.setTimeLimitType(Coupon.TIME_ABSOLUTELY);
                          },
                          child: Row(
                            children: <Widget>[
                              Container(
                                child: Text('有效时期'),
                                margin: EdgeInsets.only(
                                  right: 30.w,
                                ),
                              ),
                              Expanded(
                                child: CalendarBar(
                                  enabled: provider.isCouponOn,
                                  startDateTime: provider.beginDateTime,
                                  endDateTime: provider.endDateTime,
                                  onDateTimeChanged: provider.setBeginTime,
                                ),
                              ),
                            ],
                          ),
                        ),
                        _RadioRow(
                          isSelected: provider.coupon.timeLimitType == Coupon.TIME_TODAY,
                          onSelectedChange: (_) {
                            provider.setTimeLimitType(Coupon.TIME_TODAY);
                          },
                          child: Row(
                            children: <Widget>[
                              Container(
                                child: Text('领券当日起'),
                                margin: EdgeInsets.only(
                                  right: 20.w,
                                ),
                              ),
                              Container(
                                width: 160.w,
                                margin: EdgeInsets.only(
                                  right: 7.w,
                                ),
                                child: BaseTextFormField(
                                  hintText: '请输入',
                                  enabled: provider.isCouponOn,
                                  textAlign: TextAlign.center,
                                  keyboardType: TextInputType.number,
                                  initialValue: provider.startTodayText,
                                  onChanged: provider.setStartToday,
                                  focusNode: startTodayFocusNode,
                                  inputFormatters: [FilteringTextInputFormatter.allow(RegUtil.integerReg)],
                                ),
                              ),
                              Text('天'),
                            ],
                          ),
                        ),
                        _RadioRow(
                          isSelected: provider.coupon.timeLimitType == Coupon.TIME_TOMORROW,
                          onSelectedChange: (_) {
                            provider.setTimeLimitType(Coupon.TIME_TOMORROW);
                          },
                          child: Row(
                            children: <Widget>[
                              Container(
                                child: Text('领券次日起'),
                                margin: EdgeInsets.only(
                                  right: 20.w,
                                ),
                              ),
                              Container(
                                width: 160.w,
                                margin: EdgeInsets.only(
                                  right: 7.w,
                                ),
                                child: BaseTextFormField(
                                  enabled: provider.isCouponOn,
                                  hintText: '请输入',
                                  textAlign: TextAlign.center,
                                  keyboardType: TextInputType.number,
                                  initialValue: provider.startTomorrowText,
                                  onChanged: provider.setStartTomorrow,
                                  focusNode: startTomorrowFocusNode,
                                  inputFormatters: [FilteringTextInputFormatter.allow(RegUtil.integerReg)],
                                ),
                              ),
                              Text('天'),
                            ],
                          ),
                        ),
                      ],
                    ),
                    PackagePanel(
                      title: '领券次数',
                      subtitle: '(未填则不限制，超限制次数，提示用户无法领券）',
                      isRequired: true,
                      contentPadding: EdgeInsets.zero,
                      padding: EdgeInsets.zero,
                      children: <Widget>[
                        _RadioRow(
                          isSelected: provider.coupon.personLimitNum != null,
                          isShowIcon: false,
                          child: Row(
                            children: <Widget>[
                              Container(
                                child: Text('限领次数'),
                                margin: EdgeInsets.only(),
                              ),
                              Container(
                                width: 120.w,
                                margin: EdgeInsets.only(),
                                child: BaseTextFormField(
                                  enabled: provider.isCouponOn,
                                  hintText: '请输入',
                                  textAlign: TextAlign.center,
                                  keyboardType: TextInputType.number,
                                  initialValue: provider.coupon?.personLimitNum?.toString(),
                                  onChanged: provider.setPersonLimitNum,
                                  inputFormatters: [FilteringTextInputFormatter.allow(RegUtil.integerReg)],
                                ),
                              ),
                              Text('次'),
                              Text(
                                '',
                                style: TextStyleConstant().normal_3_24,
                              ),
                            ],
                          ),
                        ),
                      ],
                    ),
                    PackagePanel(
                      title: '到期提醒',
                      contentPadding: EdgeInsets.zero,
                      padding: EdgeInsets.zero,
                      children: <Widget>[
                        _RadioRow(
                          isSelected: provider.coupon.advanceNoticeDays != null,
                          isShowIcon: false,
                          child: Row(
                            children: <Widget>[
                              Text('优惠券到期前'),
                              Container(
                                width: 160.w,
                                child: BaseTextFormField(
                                  enabled: provider.isCouponOn,
                                  hintText: '请输入',
                                  textAlign: TextAlign.center,
                                  keyboardType: TextInputType.number,
                                  initialValue: provider.coupon.advanceNoticeDays?.toString(),
                                  onChanged: provider.setAdvanceNoticeDays,
                                  inputFormatters: [FilteringTextInputFormatter.allow(RegUtil.integerReg)],
                                ),
                              ),
                              Text('天，提醒用户使用')
                            ],
                          ),
                        ),
                      ],
                    ),
                    GestureDetector(
                      onTap: provider.isCouponOn
                          ? () async {
                              final response = await showEditCouponShareModal(
                                context,
                                provider.coupon.shareTitle,
                                provider.coupon.shareImageUrl,
                              );
                              provider.setShareMessage(response);
                            }
                          : null,
                      behavior: HitTestBehavior.translucent,
                      child: PackagePanel(
                        title: '分享页编辑',
                        isRequired: true,
                        contentPadding: EdgeInsets.zero,
                        padding: EdgeInsets.zero,
                        actions: <Widget>[
                          LabelButton(
                            title: '编辑',
                          ),
                        ],
                        children: <Widget>[
                          Text(
                            provider.coupon.shareTitle ?? '请输入分享标题',
                            style: TextStyleConstant().normal_4_28,
                          ),
                          Container(
                            margin: EdgeInsets.symmetric(
                              vertical: 30.w,
                            ),
                            child: UploadImage(
                              height: 550.w,
                              uploadedImage: provider.coupon.shareImageUrl,
                              enabled: false,
                            ),
                          ),
                        ],
                      ),
                    ),
                    PackagePanel(
                      title: '优惠券描述',
                      isRequired: true,
                      padding: EdgeInsets.only(
                        bottom: 30.w
                      ),
                      children: [
                        LongTextFormField(
                          hintText: '请输入优惠券描述',
                          maxLength: 120,
                          maxLines: 8,
                          initValue: provider.coupon.couponDescribe,
                          onChanged: provider.setCouponDescribe,
                        ),
                      ],
                    ),
                  ],
                ),
              ),
            ),
            if (provider.coupon.usingStatus != Coupon.STATUS_OFF)
              FixedBottomBtn(
                title: '保 存',
                onTap: Provider.of<CouponDetailProvider>(context, listen: false).saveCoupon,
              ),
            if (provider.coupon.usingStatus == Coupon.STATUS_OFF)
              FixedBottomBtn(
                title: '复 制',
                onTap: Provider.of<CouponDetailProvider>(context, listen: false).copyCoupon,
              ),
          ],
        ),
      ),
    );
  }
}

class _RadioRow extends StatelessWidget {
  final bool isSelected;
  final Widget child;
  final bool isShowIcon;
  final ValueChanged<bool> onSelectedChange;

  const _RadioRow({
    @required this.child,
    this.isSelected = false,
    this.isShowIcon = true,
    this.onSelectedChange,
    Key key,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: onSelectedChange == null ? null : () => onSelectedChange(!isSelected),
      behavior: HitTestBehavior.deferToChild,
      child: Container(
        constraints: BoxConstraints(
          minHeight: 90.w,
        ),
        alignment: Alignment.centerLeft,
        child: Row(
          children: <Widget>[
            if (isShowIcon)
              Container(
                margin: EdgeInsets.only(right: 15.w),
                child: radio.Radio(
                  selectedIcon: 'assets/image/radio_checked_icon.png',
                  unSelectedIcon: 'assets/image/radio_unchecked_icon.png',
                  isSelected: isSelected,
                ),
              ),
            Expanded(child: child),
          ],
        ),
      ),
    );
  }
}
